﻿using System;
using System.Linq;
using iss.sg4210.se18.team6s.jass.DAL;
using iss.sg4210.se18.team6s.jass.DAL.DataAccess.Interfaces;

namespace iss.sg4210.se18.team6s.jass.BL
{
    public class GeoAreaFacade
    {
        IGeographicalArea geographicalAreaRepo = null;
        public GeoAreaFacade()
        {
            geographicalAreaRepo = DataAccessFactory.Instance.GeographicalArea;
        }

        public IQueryable<GeoArea> FindAllGeographicalAreas()
        {
            try
            {
                return geographicalAreaRepo.FindAllGeographicalAreas();
            }
            catch (Exception ex)
            {
                throw new JASSException(JASSConstants.JASS_ERROR_RETRIEVE, ex);
            }
        }

        public GeoArea GetGeographicalArea(int id)
        {
            try
            {
                return geographicalAreaRepo.GetGeographicalArea(id);
            }
            catch (Exception ex)
            {
                throw new JASSException(JASSConstants.JASS_ERROR_RETRIEVE, ex);
            }
        }

        public void AddGeographicalArea(GeoArea g)
        {
            IQueryable<GeoArea> locations = FindAllGeographicalAreas();
            if (locations.Count(m => m.Name == g.Name) > 0)
                throw new JASSException("Duplicate Location with same Title '" + g.Name + "' found!");

            try
            {
                geographicalAreaRepo.AddGeographicalArea(g);
            }
            catch (Exception ex)
            {
                throw new JASSException(JASSConstants.JASS_ERROR_SAVE, ex);
            }
        }

        public void UpdateGeographicalArea(GeoArea g)
        {
            try
            {
                geographicalAreaRepo.UpdateGeographicalArea(g);
            }
            catch (Exception ex)
            {
                throw new JASSException(JASSConstants.JASS_ERROR_UPDATE, ex);
            }
        }

        public void DeleteGeographicalArea(int id)
        {

            GeoArea geoArea = GetGeographicalArea(id);
            if (geoArea.Advertisements.Count > 0)
                throw new JASSException("Cannot delete Location '" + geoArea.Name + "'. It has one or more Advertisements!");

            try
            {
                geographicalAreaRepo.DeleteGeographicalArea(id);
            }
            catch (Exception ex)
            {
                throw new JASSException(JASSConstants.JASS_ERROR_DELETE, ex);
            }
        }
    }
}
